package com.controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by 张 on 2018/5/25.
 */
@RestController
@RequestMapping("/test")
public class TestController {


    @RequestMapping(value="/jsonToSql",method = RequestMethod.POST)
    public String jsonToSql(@RequestBody String jsonStr) {
        System.out.println("test:"+jsonStr);
        return jsonToSqlUtil(jsonStr);
    }

    private String jsonToSqlUtil(String jsonStr){
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);
        System.out.println("size:"+jsonObject.size());

        StringBuffer result = new StringBuffer();
        result.append("CASE");
        result.append("\r\n");
        for (int i = 0; i <jsonObject.size() ; i++) {


            JSONArray jsonArray = jsonObject.getJSONArray("LogicCode_"+(i+1));
            result.append("WHEN ");
            for (int j = 1; j <jsonArray.size()+1 ; j++) {
                JSONObject object = jsonArray.getJSONObject(j-1);

                if(j==1 && jsonArray.size()>1){
                    result.append("(");
                }

                result.append("( "+object.getString("fieldName")+" "+object.getString("op")+" "+object.getString("value")+" )");

                if(StringUtils.isNotEmpty(object.getString("condition"))){
                    result.append(" "+object.getString("condition")+" ");
                }

                if(j==jsonArray.size() && jsonArray.size()>1){
                    result.append(")");
                }

                if(j==jsonArray.size()){
                    result.append(" THEN '"+object.getString("result")+"'");
                    if(object.get("otherwise")!=null && StringUtils.isNotEmpty(object.getString("otherwise"))){
                        result.append(" ELSE '"+object.getString("otherwise")+"'");
                    }
                    result.append("\r\n");
                }

            }


        }
        result.append("END");
        return result.toString();
    }

}
